#!/usr/bin/env python

from liwe.module import LiweModule

class TextPage ( LiweModule ):

	def __init__ ( self, liwe ):
		super ( TextPage, self ).__init__ ( liwe, "text_page" )

		self.dbm = self.liwe.dbm


	def add ( self, title, text, id_page = 0, id_page_man = 0, tags = '', perms = 644 ):
		# Inserisco i dati nel page manager
		id_page_man = self.liwe.invoke ( "page_manager.admin.create", text, id_page_man, "text_page" ) [ 'id_page' ]
		
		dct = { "title": title, "id_page_man" : id_page_man }

		if not id_page:
			dct [ 'created' ] = "*NOW()"

			self.dbm.insert ( "text_page", dct )
			id_page = self.dbm.insert_id ()
		else:
			self.dbm.update ( "text_page", dct, "id_page = %s" % id_page )

		# save tags
		self.liwe.invoke ( "tags.admin.del_all_tags", id_obj = id_page, id_site = self.site_id, module = "text_page" )
		self.liwe.invoke ( "tags.ajax.tag_object", id_obj = id_page, id_site = self.site_id, tags = tags, module = "text_page" )
		return id_page

	def delete ( self, id_page ):
		vals = self.dbm.single_row ( "text_page", "id_page_man", "id_page = '%s'" % id_page )

		self.liwe.invoke ( "page_manager.admin.delete", vals [ 'id_page_man' ] )
		self.dbm.delete ( "text_page", "id_page = '%s'" % id_page )

		#Cancello i tags
		self.liwe.invoke ( "tags.ajax.del_all_tags", id_obj = id_page, id_site = self.site_id, module = 'text_page' )


	def get ( self, id_page ):
		vals =  self.dbm.single_row ( [ "text_page AS tp", "page AS p" ], 
						[ "tp.id_page", "tp.title", "tp.created", "tp.id_page_man",
						"p.txt" ],
						"p.id_page = tp.id_page_man AND tp.id_page = %s" % id_page )
					
		if vals:
			tags = self.liwe.invoke ( "tags.ajax.tags_list", id_obj = vals [ "id_page" ], 
						id_site = self.site_id, module = 'text_page' )
			vals [ "tags" ] = tags [ "tags" ]

		return vals

	def list ( self ):
		res = self.dbm.all_rows ( "text_page", [ "id_page", "title" ], extras = "ORDER BY id_page" )
		if not res: return []

		return res
